package work02.w5.control.persistence;


import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 一个能将对象序列写入的类
 * 
 * @author Eric
 * 
 */
public class FileSaveLoadSystemByXML {

	public FileSaveLoadSystemByXML() {
	}

	public boolean save(String location, Object o) throws IOException {
		FileOutputStream out = null;
		try {
			File file = new File(location + ".xml");
			file.mkdirs();
			if (!file.exists())
				file.createNewFile();// 如果文件不存在，创建新文件

			out = new FileOutputStream(file);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		XMLEncoder xm = new XMLEncoder(out);
		xm.writeObject(o);
		xm.flush();
		xm.close();
		try {
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}

	public Object load(String location) {
		FileInputStream in = null;
		try {
			File file = new File(location + ".xml");
			if (!file.exists())
				return null;// 如果文件不存在，返回为空

			in = new FileInputStream(file);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return null;
		}

		XMLDecoder xm = new XMLDecoder(in);
		Object temp = xm.readObject();

		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return temp;
	}

}
